package es.mgil.barriguitas;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

public class Barriguitas extends Activity {
	private Button startButton;
	private Button closeButton;
	private ProgressBar progressBar;
	private TextView label;
	private EditText text;

	private ApnSettings apn;

	private Thread thread;
	private boolean processing = false;

	private PowerManager.WakeLock wl;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "DoNotDimScreen");

		setContentView(R.layout.main);

		apn = new ApnSettings(getContentResolver());

		startButton = (Button) this.findViewById(R.id.buttonStart);
		startButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					thread = new Thread(myRunnable);
					processing = true;
					thread.start();
				} catch (Exception e) {
					try {
						thread.stop();
					} catch (Exception e2) {
					}
				}
			}
		});

		closeButton = (Button) this.findViewById(R.id.buttonClose);
		closeButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				processing = false;
				apn.switchApnState(ApplicationConstants.State.ON);
				finish();
			}
		});

		text = (EditText) this.findViewById(R.id.text);
		progressBar = (ProgressBar) findViewById(R.id.progressbar);
		label = (TextView) findViewById(R.id.text2);
	}

	@Override
	protected void onPause() {
		super.onPause();
		wl.release();
	}

	@Override
	protected void onResume() {
		super.onResume();
		wl.acquire();
	}

	private Runnable myRunnable = new Runnable() {
		@Override
		public void run() {
			start();
		}
	};

	private void start() {
		// if connected, disconnect and wait for disconnection
		if (apn.getApnState() == ApplicationConstants.State.ON) {
			apn.switchApnState(ApplicationConstants.State.OFF);
			while (getMobileNetwork().getState() != State.DISCONNECTED) {
				sleep(200);
			}
		}

		String s = text.getText().toString();
		final int sendings = Integer.parseInt(s);

		// disable start button and editText
		handleEnableDisable.value = false;
		handleEnableDisable.sendMessage(handleEnableDisable.obtainMessage());

		// initialize progress bar and label
		handleUpdateWidgets.sendings = sendings;
		handleUpdateWidgets.step = 0;
		handleUpdateWidgets.sendMessage(handleUpdateWidgets.obtainMessage());

		for (int step = 1; processing && step <= sendings; step++) {
			// if disconnected, connect and wait for connection
			if (apn.getApnState() == ApplicationConstants.State.OFF) {
				apn.switchApnState(ApplicationConstants.State.ON);
				while (getMobileNetwork().getState() != State.CONNECTED) {
					sleep(200);
				}
			}

			// send the message
			boolean result = false;
			while (!result) {
				result = sendMessage();
			}

			// update progress bar and label
			handleUpdateWidgets.step = step;
			handleUpdateWidgets
					.sendMessage(handleUpdateWidgets.obtainMessage());

			// if connected, disconnect and wait for disconnection
			if (apn.getApnState() == ApplicationConstants.State.ON) {
				apn.switchApnState(ApplicationConstants.State.OFF);
				while (getMobileNetwork().getState() != State.DISCONNECTED) {
					if (getMobileNetwork().getState() == State.CONNECTED) {
						apn.switchApnState(ApplicationConstants.State.OFF);
					}
					sleep(200);
				}
			}
		}

		// if disconnected, connect and wait for connection
		if (apn.getApnState() == ApplicationConstants.State.OFF) {
			apn.switchApnState(ApplicationConstants.State.ON);
		}

		// enable start button and editText
		handleEnableDisable.value = true;
		handleEnableDisable.sendMessage(handleEnableDisable.obtainMessage());
	}

	private MyHandleButton handleEnableDisable = new MyHandleButton();

	private class MyHandleButton extends Handler {
		public boolean value;

		@Override
		public void handleMessage(Message msg) {
			startButton.setEnabled(value);
			text.setEnabled(value);
		}
	}

	private MyHandleProgressBar handleUpdateWidgets = new MyHandleProgressBar();

	private class MyHandleProgressBar extends Handler {
		public int step;
		public int sendings;

		@Override
		public void handleMessage(Message msg) {
			int value = Math.min((step * 100) / sendings, 100);
			progressBar.setProgress(value);
			label.setText(String.valueOf(step) + "/" + sendings);
		}
	}

	private boolean sendMessage() {
		try {
			URLConnection conn = getURLConnection();
			String body = getBody();

			OutputStreamWriter wr = new OutputStreamWriter(
					conn.getOutputStream());
			wr.write(body);
			wr.flush();

			// InputStream is = conn.getInputStream();
			// int c;
			// while ((c = is.read()) != -1) {
			// System.out.print((char) c);
			// }
			// is.close();

			return true;
		} catch (IOException e) {
			return false;
		}
	}

	private URLConnection getURLConnection() {
		try {
			URL url = new URL(
					"http://www.labarrigamasguapa.com/scripts/inquerito_vote.aspx");
			URLConnection conn = url.openConnection();
			conn.setRequestProperty("Host", "www.labarrigamasguapa.com");
			conn.setRequestProperty("Connection", "keep-alive");
			conn.setRequestProperty("Referer",
					"http://www.labarrigamasguapa.com/barrigaguapa2.swf");
			conn.setRequestProperty("Content-Lenght", "165");
			conn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			conn.setRequestProperty("Accept", "*/*");
			conn.setRequestProperty(
					"User-Agent",
					"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.8 Safari/534.7");
			conn.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
			conn.setRequestProperty("Accept-Language", "es-ES,es;q=0.8");
			conn.setRequestProperty("Accept-Charset",
					"ISO-8859-1,utf-8;q=0.7,*;q=0.3");
			conn.setRequestProperty(
					"Cookie",
					"__utmz=161847329.1285100776.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utma=161847329.1032130988.1285100776.1285100776.1285407792.2; __utmc=161847329; __utmb=161847329.1.10.1285407792");

			conn.setDoOutput(true);
			conn.setDoInput(true);

			return conn;
		} catch (MalformedURLException e) {
			return null;
		} catch (IOException e) {
			return null;
		}
	}

	private String getBody() {
		return "idd=251&infouser=1366%3A768%2FWIN+10%2C1%2C82%2C76%2FWindows+7%2Fes%2FGoogle+Windows%2F72%2FMP3%3Atrue%2FAudio%3Atrue%2FAudioE%3Atrue%2FvideoE%3Atrue%2FAccess%3Atrue";
	}

	private NetworkInfo getMobileNetwork() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
		NetworkInfo network = null;
		for (NetworkInfo ni : cm.getAllNetworkInfo()) {
			if (ni.getTypeName().equals("mobile")) {
				network = ni;
				break;
			}
		}
		return network;
	}

	private void sleep(int num) {
		try {
			Thread.sleep(num);
		} catch (InterruptedException e) {
		}
	}
}